package com.sohu.peak.gallery.dao.hibernate;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.sohu.peak.gallery.dao.PicAttributeDAO;
import com.sohu.peak.gallery.domain.Pic;
import com.sohu.peak.gallery.domain.PicAttribute;
import com.sohu.peak.util.Logger;

public class PicAttributeHibernateDAO extends BaseHibernateDAO implements PicAttributeDAO{
	
	private static final Logger log = new Logger();
	
	public void saveOrUpdate(List<PicAttribute> picAttributes) {
		log.debug("saving picAttribute instance!!!");
		try {
			Session session=this.getSession();
			for( PicAttribute picAttribute : picAttributes){
				session.saveOrUpdate(picAttribute);
			}
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
		
	}

	public PicAttribute findByPicId(Long picId) {
		// TODO Auto-generated method stub
		log.debug("getting PicAttribute instance with picId: " + picId);
		try {
			PicAttribute instance = (PicAttribute) getSession().get(
					"com.sohu.peak.gallery.domain.PicAttribute", picId);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public void delByPicIds(List ids) {
		// TODO Auto-generated method stub
		StringBuffer arr=new StringBuffer("(");
    	Iterator it=ids.iterator();
    	int i=ids.size();
    	while(it.hasNext()){
    		Long id=(Long) it.next();
    		if(i==1){
    			arr.append(id+")");
    		}else{
    			arr.append(id+",");
    		}
    		i--;
    	}
    	if(ids.size()>0){
    		String idStrs=arr.toString();
        	String queryStr="delete from PicAttribute pa where pa.picId in "+idStrs;
        	log.info(queryStr);
    		this.getSession().createQuery(queryStr).executeUpdate();
    	}
    	
	}

	public List findByProperty(String propertyName, Object value) {
	
		
		log.debug("finding PicAttribute instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from PicAttribute as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByPicGroupId(Long pid) {
		String sql="from PicAttribute as model where model.groupId="+pid;
		Query query=this.getSession().createQuery(sql);
		return query.list();
	}


}
